package com.junki.officecontentsearch.controller;

import cn.hutool.core.io.CharsetDetector;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.junki.officecontentsearch.entity.IndexFile;
import com.junki.officecontentsearch.service.IndexFileService;
import com.junki.officecontentsearch.util.FileUploadService;
import com.junki.officecontentsearch.util.OfficeUtil;
import com.junki.officecontentsearch.vo.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @author junki
 * @date 2021/5/28 14:17
 */
@Slf4j
@RestController
@RequestMapping("file")
public class FileController {

    @Resource
    private IndexFileService indexFileService;

    @Resource
    private FileUploadService fileUploadService;

    // 内容关键字查询
    @RequestMapping("searchContent")
    public JsonResult searchContent(@RequestParam("keyword") String keyword, @RequestParam("matchQuery") Boolean matchQuery) {

        List<IndexFile> indexFiles = indexFileService.findByContentKeyword(keyword, matchQuery);

        return JsonResult.builder().code(200).msg("查询成功").data(indexFiles).build();
    }

    // 上传文件
    @RequestMapping("upload")
    public JsonResult upload(@RequestParam("file") MultipartFile file) throws IOException {

        // 获取原文件名
        String originalFilename = file.getOriginalFilename();

        // 文件名不能为空
        if (StrUtil.isBlank(originalFilename)) {
            throw new RuntimeException("文件名不能为空");
        }

        // 获取文件后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);

        // 文件后缀不能为空
        if (StrUtil.isBlank(originalFilename)) {
            throw new RuntimeException("文件后缀不能为空");
        }

        // 生成保存文件名
        String saveName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS")) + "." + suffix;

        // 根据不同的文件类型调用不同的方法获取内容
        String content;
        switch (suffix) {
            case "doc":
            case "docx":
                content = OfficeUtil.getWordContent(file);
                // 异步保存文件
                fileUploadService.asyncSaveFile(file, saveName);
                break;
            case "xls":
            case "xlsx":
                content = OfficeUtil.getExcelContent(file);
                // 异步保存文件
                fileUploadService.asyncSaveFile(file, saveName);
                break;
            case "pdf":
                content = OfficeUtil.getPdfContent(file);
                // 异步保存文件
                fileUploadService.asyncSaveFile(file, saveName);
                break;
            case "txt":
                // 同步保存文件
                File saveFile = fileUploadService.syncSaveFile(file, saveName);
                // 探测文件字符编码
                Charset charset = CharsetDetector.detect(new FileInputStream(saveFile));
                content = FileUtil.readString(saveFile, charset);
                break;
            default:
                throw new RuntimeException("该类型文件不支持");
        }

        // 保存数据到es
        IndexFile indexFile = IndexFile.builder().id(IdUtil.fastSimpleUUID()).filename(originalFilename).saveName(saveName).type(suffix).content(content).build();
        indexFileService.add(indexFile);

        return JsonResult.builder().code(200).msg("上传成功").data(content).build();

    }


}
